
import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:massagist/manager/request.dart';
import 'package:massagist/pages/privacy_page.dart';
import 'package:massagist/pages/tab_page.dart';
import 'package:toast/toast.dart';

import '../generated/l10n.dart';
import '../manager/config.dart';

class PhoneLoginPage extends StatefulWidget {
  @override
  State<PhoneLoginPage> createState() => PhoneLoginPageState();
}

class PhoneNumberFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    final text = newValue.text;

    if (text.length <= 3) {
      return newValue;
    }

    String formatted = '';

    for (int i = 0; i < text.length; i++) {
      formatted += text[i];
      if (i == 2) {
        formatted += '-';
      }
    }

    return newValue.copyWith(
      text: formatted,
      selection: TextSelection.collapsed(offset: formatted.length),
    );
  }
}

class PhoneLoginPageState extends State<PhoneLoginPage> {
  String phoneValue = "39999912345";
  String codeValue = "12345";
  int cutDown = -1;

  void codeCutdown() {
    cutDown = 60;
    Timer.periodic(Duration(seconds: 1), (timer) {
      cutDown--;
      if (cutDown < 0) {
        timer.cancel();
      }

      setState(() {
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            GestureDetector(
              child: Container(
                margin: EdgeInsets.only(top: 59.sp, left: 17.sp),
                child: Icon(Icons.close),
              ),
              onTap: () {
                Navigator.pop(context);
              },
            ),

            Container(
              margin: EdgeInsets.only(top: 150.sp, left: 32.sp, right: 32),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    height: 21.sp,
                    alignment: Alignment.center,
                    child: TextField(
                      controller: TextEditingController(text: phoneValue),
                      inputFormatters: [
                        FilteringTextInputFormatter.digitsOnly,
                        LengthLimitingTextInputFormatter(10),
                        PhoneNumberFormatter(),
                      ],

                      textAlignVertical: TextAlignVertical.center,
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: S.current.INPUT_PHONE_REMIND,
                          hintStyle: TextStyle(color: Color(0xFF999999), fontSize: 15)
                      ),
                      style: TextStyle(color: Color(0xFF333333), fontSize: 15),
                      onChanged: (text) {
                        phoneValue = text;
                      },
                    ),
                  ),
                  Container(
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          margin: EdgeInsets.only(top: 40.sp),
                          width: 100.sp,
                          height: 21.sp,
                          alignment: Alignment.center,
                          child: TextField(
                            controller: TextEditingController(text: codeValue),
                            inputFormatters: [
                              FilteringTextInputFormatter.allow(RegExp(
                                  '[0-9]')),
                              LengthLimitingTextInputFormatter(15),
                            ],
                            maxLength: MAX_CODE_LEHGTH,
                            // obscureText: true,
                            textAlignVertical: TextAlignVertical.center,
                            decoration: InputDecoration(
                                border: InputBorder.none,
                                counterText: "",
                                hintText: S.current.INPUT_CODE_REMIND,
                                hintStyle: TextStyle(color: Color(0xFF999999), fontSize: 15.sp)
                            ),
                            style: TextStyle(color: Color(0xFF333333), fontSize: 15.sp),
                            onChanged: (text) {
                              codeValue = text;
                            },
                          ),
                        ),
                        GestureDetector(
                          child: Container(
                            height: 21.sp,
                            child: Text(cutDown > 0 ? cutDown.toString() + "s" : S.current.GET_CODE, style: TextStyle(
                              color: Color(0xFF00CA7E),
                              fontSize: 14.sp,
                            )),
                          ),
                          onTap: () async {
                            if (cutDown > 0) {
                              return;
                            }

                            var codeResult = await Request.requestCode(phoneValue);
                            if (codeResult.code == RESPONSE_SUCCESS) {
                              codeCutdown();
                            } else {
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(content: Text(codeResult.msg)),
                              );
                            }
                          },
                        )
                      ],
                    ),
                  ),

                  GestureDetector(
                    child: Container(
                      width: double.infinity,
                      height: 44.sp,
                      margin: EdgeInsets.only(top: 57.sp),
                      decoration: BoxDecoration(
                        color: Color(0xFF00CA7E),
                        borderRadius: BorderRadius.circular(22.sp), // 设置圆角半径
                      ),
                      child: Center(
                        child: Text(
                          S.current.LOGIN_TEXT,
                          style: TextStyle(color: Colors.white, fontSize: 16.sp),
                        ),
                      ),
                    ),
                    onTap: () async {
                      if (checkPhone() == false) {
                        ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(S.current.INPUT_PHONE_REMIND)), );
                        return;
                      }

                      var loginResult = await Request.requestCodeLogin(phoneValue, codeValue);
                      if (loginResult.code == RESPONSE_SUCCESS) {
                        Config.userInfo = loginResult.data;
                        Config.massageUrl = await Request.requestWeb();
                        print ("网络 = " + Config.massageUrl);
                        Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (context) => TabPage()), (route) => false, );
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(loginResult.msg)), );
                      }
                    },
                  ),

                  Container(
                    margin: EdgeInsets.only(top: 28.sp),
                    alignment: Alignment.center,
                    child: RichText(
                      text: TextSpan(
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Color(0xFF999999),
                        ),
                        children: [
                          TextSpan(text: S.current.LOGIN_RIGHT_AGREE),
                          TextSpan(
                            text: S.current.LOGIN_RIGHT_PRIVACY,
                            style: TextStyle(
                              color: Color(0xFF00CA7E),
                            ),
                            recognizer: TapGestureRecognizer()..onTap = () {
                              Navigator.push(context, MaterialPageRoute(builder: (context) => PrivacyPage()));
                            }
                          )
                        ],
                      ),
                    ),
                  )
                ],
              )
            )
          ],
        ),
      ),
    );
  }

  bool checkPhone() {
    if (phoneValue.length == MAX_PHONE_LEHGTH && codeValue.length == MAX_CODE_LEHGTH)
      return true;

    return false;
  }
}